import axios, { AxiosResponse } from 'axios'
import { getToken } from '@/utils/auth'
import emitter from '@/utils/emitter'

// API 响应接口
interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: string
}

// 登录响应接口
interface LoginResponse {
  status: string
  message: string
  data: {
    id: number
    username: string
    nickname: string
    email: string
    sex: number
    role: number
    jwt_token: string
  }
}

// 登录请求接口
interface LoginRequest {
  username: string
  password: string
}

// 新闻列表响应接口
interface NewsListResponse {
  code: number
  status: string
  data: {
    news_list: NewsItem[]
    total: number
    page: number
    page_size: number
    total_pages: number
  }
}

// 新闻详情响应接口
interface NewsDetailResponse {
  code: number
  status: string
  data: {
    news: {
      id: number
      title: string
      content: string
      created_at: string
      published_at: string | null
      status: number
      review_reason?: string
      creator_name: string
      creator_id: number
      like_count: number
      comment_count: number
      view_count: number
    }
    comments: any[]
  }
}

// 审核响应接口
interface ReviewResponse {
  code: number
  status: string
  message: string
}

// 用户列表接口
interface UsersListResponse {
  code:number
  status:string
  data: {
    user_list: UsersItem[]
    total: number
    page: number
    page_size: number
    total_pages: number
  }
}

// 新闻项接口
export interface NewsItem {
  id: number
  title: string
  status: number
  content: string
  created_at: string
  published_at: string
  creator_name: string
  creator_id: number
  like_count: number
  comment_count: number
  view_count: number
}

// 用户项接口
export interface UsersItem {
  id: number
  username: string
  nickname: string
  email: string
  role: number
  status: number
  created_at: string
}

// 新闻列表查询参数
interface NewsListParams {
  page?: number
  rows?: number
}

// 新闻列表查询参数
interface UsersListParams {
  page?: number
  rows?: number
}

// 文件列表查询参数
interface FileListParams {
  page?: number
  rows?: number
}

// 文件项接口
export interface FileItem {
  id: number
  filename: string
  file_size: number
  file_url: string
  file_type: string
  file_md5: string
  upload_user_id: number | null
  created_at: string
  updated_at: string
  username: string | null
  nickname: string | null
}

// 文件列表响应接口
interface FileListResponse {
  code: number
  status: string
  data: {
    file_list: FileItem[]
    total: number
    page: number
    page_size: number
    total_pages: number
  }
}

// 分页参数接口
interface PaginationParams {
  page?: number
  pageSize?: number
  [key: string]: any
}

const api = axios.create({
  baseURL: '/',
  timeout: 10000,
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加请求头等通用配置
    if (config.headers) {
      config.headers['Content-Type'] = 'application/json'
      
      // 添加 JWT Token 到请求头
      const token = getToken()
      if (token) {
        config.headers['Authorization'] = token
      }
    }
    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data;

    // 检查响应体中的自定义 code
    if (data && data.code === 401) {
      emitter.emit('unauthorized');
      return Promise.reject({
        success: false,
        error: data.message || '登录已过期，请重新登录',
        status: 401
      });
    }

    // 统一处理响应数据
    if (data && typeof data === 'object' && data.success !== undefined) {
      return data
    }
    // 对于直接返回数据的情况，包装成标准格式
    return {
      success: true,
      data: data
    }
  },
  (error) => {
    console.error('Response error:', error)
    // 统一错误处理
    if (error.response) {
      const { status } = error.response
      
      // 处理 401 未授权错误
      if (status === 401) {
        emitter.emit('unauthorized')
        return Promise.reject({
          success: false,
          error: '登录已过期，请重新登录',
          status: 401
        })
      }
      
      // 其他服务器响应错误
      return Promise.reject({
        success: false,
        error: error.response.data?.message || error.message,
        status: error.response.status
      })
    } else if (error.request) {
      // 网络错误
      return Promise.reject({
        success: false,
        error: '网络请求失败，请检查网络连接',
        status: 0
      })
    } else {
      // 其他错误
      return Promise.reject({
        success: false,
        error: error.message || '未知错误',
        status: -1
      })
    }
  }
)

// 模拟 API 响应函数
const createMockResponse = <T>(data: T, delay = 100): Promise<ApiResponse<T>> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        data: data
      })
    }, delay)
  })
}

// API 接口定义
export const dashboardApi = {
  getStatistics: async (): Promise<ApiResponse> => {
    try {
      const response = await api.get('/mock/dashboard.json')
      return response as unknown as ApiResponse
    } catch (error) {
      console.error('Dashboard API error:', error)
      return Promise.reject(error)
    }
  },
}

export const newsApi = {
  getList: async (params: NewsListParams): Promise<NewsListResponse> => {
    try {
      console.log('parmas参数：')
      console.log(params)
      const queryParams = {
        page: params.page || 0,
        rows: params.rows || 10
      }
      const response = await api.get('http://127.0.0.1:5600/admin_panel/all_news/', { params: queryParams })
      return response.data as NewsListResponse
    } catch (error) {
      console.error('News list API error:', error)
      return Promise.reject(error)
    }
  },
  getPendingList: async (params: NewsListParams): Promise<NewsListResponse> => {
    try {
      const queryParams = {
        page: params.page || 0,
        rows: params.rows || 10
      }
      const response = await api.get('http://127.0.0.1:5600/admin_panel/news/pending/', { params: queryParams })
      return response.data as NewsListResponse
    } catch (error) {
      console.error('Pending news list API error:', error)
      return Promise.reject(error)
    }
  },
  getDetail: async (news_id: number): Promise<NewsDetailResponse> => {
    try {
      const response = await api.get(`http://127.0.0.1:5600/admin_panel/news_detail/?news_id=${news_id}`)
      return response.data as NewsDetailResponse
    } catch (error) {
      console.error('News detail API error:', error)
      return Promise.reject(error)
    }
  },
  getById: async (id: number): Promise<ApiResponse> => {
    try {
      const response = await api.get(`/mock/news.json?id=${id}`)
      return response as unknown as ApiResponse
    } catch (error) {
      console.error('News detail API error:', error)
      return Promise.reject(error)
    }
  },
  create: (data: any): Promise<ApiResponse> => {
    return createMockResponse({ id: Date.now(), ...data }, 200)
  },
  update: (id: number, data: any): Promise<ApiResponse> => {
    return createMockResponse({ id, ...data }, 200)
  },
  delete: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, deleted: true }, 200)
  },
  review: async (params: { news_id: number; status: number; review_reason?: string }): Promise<ReviewResponse> => {
    try {
      const response = await api.post('http://127.0.0.1:5600/admin_panel/news/review/', params)
      return response.data as ReviewResponse
    } catch (error) {
      console.error('News review API error:', error)
      return Promise.reject(error)
    }
  },
  approve: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, status: 'approved' }, 200)
  },
  reject: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, status: 'rejected' }, 200)
  },
}

// 添加用户请求接口
interface AddUserRequest {
  username: string
  password: string
  email: string
  role:number
  nickname: string
  sex: number

}

// 添加用户响应接口
interface AddUserResponse {
  code: number
  status: string
  message: string
  data: {
    id: number
    username: string
    nickname: string
    email: string
    sex: number
    role: number
    created_at: string
  }
}

export const userApi = {
  getList: async (params: UsersListParams): Promise<UsersListResponse> => {
    try {
      console.log('parmas参数：')
      console.log(params)
      const queryParams = {
        page: params.page || 0,
        rows: params.rows || 10
      }
      if (queryParams.page < 0) {
        queryParams.page = 0
      }
      const response = await api.get('http://127.0.0.1:5600/admin_panel/user/list/', { params:queryParams })
      return response.data as UsersListResponse
    } catch (error) {
      console.error('User list API error:', error)
      return Promise.reject(error)
    }
  },
  getById: async (id: number): Promise<ApiResponse> => {
    try {
      const response = await api.get(`/mock/users.json?id=${id}`)
      return response as unknown as ApiResponse
    } catch (error) {
      console.error('User detail API error:', error)
      return Promise.reject(error)
    }
  },
  addUser: async (data: AddUserRequest): Promise<AddUserResponse> => {
    try {
      const response = await api.post('http://127.0.0.1:5600/admin_panel/user/add_user/', data)
      return response.data as AddUserResponse
    } catch (error) {
      console.error('Add user API error:', error)
      return Promise.reject(error)
    }
  },
  create: (data: any): Promise<ApiResponse> => {
    return createMockResponse({ id: Date.now(), ...data }, 200)
  },
  update: (id: number, data: any): Promise<ApiResponse> => {
    return createMockResponse({ id, ...data }, 200)
  },
  delete: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, deleted: true }, 200)
  },
  approveCreator: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, creatorStatus: 'approved' }, 200)
  },
  rejectCreator: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, creatorStatus: 'rejected' }, 200)
  },
}

export const commentApi = {
  getList: async (params?: PaginationParams): Promise<ApiResponse> => {
    try {
      const response = await api.get('/mock/comments.json', { params })
      return response as unknown as ApiResponse
    } catch (error) {
      console.error('Comment list API error:', error)
      return Promise.reject(error)
    }
  },
  delete: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, deleted: true }, 200)
  },
  hide: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, hidden: true }, 200)
  },
  show: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, hidden: false }, 200)
  },
}

export const reportApi = {
  getList: async (params?: PaginationParams): Promise<ApiResponse> => {
    try {
      const response = await api.get('/mock/reports.json', { params })
      return response as unknown as ApiResponse
    } catch (error) {
      console.error('Report list API error:', error)
      return Promise.reject(error)
    }
  },
  handle: (id: number, result: string): Promise<ApiResponse> => {
    return createMockResponse({ id, result, handled: true }, 200)
  },
  approve: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, status: 'approved' }, 200)
  },
  reject: (id: number): Promise<ApiResponse> => {
    return createMockResponse({ id, status: 'rejected' }, 200)
  },
}

export const fileApi = {
  getList: async (params: FileListParams): Promise<FileListResponse> => {
    try {
      const queryParams = {
        page: params.page || 0,
        rows: params.rows || 10
      }
      if (queryParams.page < 0) {
        queryParams.page = 0
      }
      const response = await api.get('http://127.0.0.1:5600/api/files/', { params: queryParams })
      return response.data as FileListResponse
    } catch (error) {
      console.error('File list API error:', error)
      return Promise.reject(error)
    }
  },
}

// 认证相关API
export const authApi = {
  login: async (credentials: LoginRequest): Promise<LoginResponse> => {
    try {
      const response = await api.post('http://127.0.0.1:5600/admin_panel/login/', credentials)
      return response.data as LoginResponse
    } catch (error) {
      console.error('Login API error:', error)
      return Promise.reject(error)
    }
  },
  logout: async (): Promise<ApiResponse> => {
    try {
      // 清除本地存储的token
      localStorage.removeItem('jwt_token')
      localStorage.removeItem('user_info')
      return {
        success: true,
        message: '退出登录成功'
      }
    } catch (error) {
      console.error('Logout error:', error)
      return Promise.reject(error)
    }
  }
}

export default api
